<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Google Maps JavaScript API v3 Example: Directions Complex</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/standard.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style>
  body{
	text-align:center;
  }
  #map_canvas{
	margin: 20px auto;
	border: 1px dashed #C0C0C0;
	width: 800px;
	height: 500px;
  }
	#geocode{
		position:absolute;
		left:10px;
		top:10px;
		width:250px;
		background-color:yellow;
	}
</style>

<script type="text/javascript">
  //将变量设置为全局变量方便方法调用
  var map;
	var directionDisplay;
  var directionsService;

  function initialize() {
		//注册一个路线服务
		directionsService = new google.maps.DirectionsService();
		//注册一个渲染路线的对象
		directionsDisplay = new google.maps.DirectionsRenderer();
		
    var latlng = new google.maps.LatLng(30.33508, 114.17211);
    var myOptions = {
      zoom: 10,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		//在地图上渲染路线
		directionsDisplay.setMap(map);
  }

	//生成路线的方法
	function calcRoute() {
		var start = document.getElementById("start").value;
	  var end = document.getElementById("end").value;
		var selectedMode = document.getElementById("mode").value;
		if(selectedMode == "BICYCLING") {
			alert("对不起！自行车道和偏爱街道的骑车路线只能在美国地图使用！");
			return;
		}
		//声明一个DirectionsRequest对象
		var request = {
			origin: start,
			destination: end,
			travelMode: google.maps.DirectionsTravelMode[selectedMode]
		};
		/*发出路线搜索请求，改方法接收两个参数，第一个是一个DirectionsRequest对象，
			第二个是一个回调函数，该函数也是接收两个参数，分别是DirectionsResult, DirectionsStatus两个类型的，
			DirectionsResult参数是路线以从路线服务器检索的 JSON 格式进行响应，用与 DirectionsRenderer 渲染这些路线，
			DirectionsStatus是route() 的调用时由 DirectionsService 传回的状态
		*/
		directionsService.route(request, function(response, status) {
			if(status == google.maps.DirectionsStatus.OK) {
				directionsDisplay.setDirections(response);
			}
		});
	}
</script>
</head>
<body onload="initialize()">
	<div id="geocode">
    起点：<input id="start" type="text" value="华中科技大学文华学院"><br>
		终点：<input id="end" type="text" value="光谷软件园"><br>
		Mode of Travel: 
		<select id="mode">
			<option value="DRIVING">Driving</option>
			<option value="WALKING">Walking</option>
			<option value="BICYCLING">Bicycling</option>
		</select>
    <input type="button" value="提交" onclick="calcRoute();">
	</div>
  <div id="map_canvas"></div>
</body>
</html>